package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.pop.RepayNumberKeyBoardPop;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.LoansUtils;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.widget.CustomPhoneCodeView;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * Description: 支付密码 第一步 短信
 * Created by FHW
 * on 2017/11/9
 */

public class RepaymentPwdOneActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.v_phone_code)
    CustomPhoneCodeView v_phone_code;
    @BindView(R.id.tv_code)
    TextView tv_code;
    @BindView(R.id.tv_mobile)
    TextView tv_mobile;

    private RepayNumberKeyBoardPop pop;
    private String tranKey = "";
    private MyCountDownTimer timer;

    private int type = 0;//0-设置 1- 修改
    private String mPhone = "";
    private String msgCode = "";

    @Override

    protected int getLayoutId() {
        return R.layout.activity_repayment_pwd_one;
    }

    @OnClick({R.id.v_phone_code, R.id.tv_code})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.v_phone_code:
                showPopKeyboard();
                break;
            case R.id.tv_code:
                SelfUtils.buriedClickData(Self.Action.app_click_modify_payment_pwd_send_sms,
                        Self.Action.app_click_modify_payment_pwd_send_sms_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                sendMsgCode(mPhone);
                break;
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        title_bar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId= Self.Page.app_modify_pay_pwd_sms_verify_page;

        type = getIntent().getIntExtra("type", 0);
        switch (type) {
            case 0:
                title_bar.setTitleText("设置支付密码");
                break;
            case 1:
                title_bar.setTitleText("修改支付密码");
                break;
        }

        if (mApplication.getUser() != null && !TextUtils.isEmpty(mApplication.getUser().getPhone())) {
            mPhone = mApplication.getUser().getPhone();
            if (mPhone.length() == 11) {
                tv_mobile.setText(mPhone.substring(0, 3) + "****" + mPhone.substring(7));
            }
        }

        sendMsgCode(mPhone);

    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            showPopKeyboard();
        }
        super.onWindowFocusChanged(hasFocus);
    }

    private void showPopKeyboard() {
        if (pop == null) {
            pop = new RepayNumberKeyBoardPop(mContext);
            pop.setNumberKeyListener(new RepayNumberKeyBoardPop.OnKeyPressed() {
                @Override
                public void onKeyPressed(int key) {
                    StringBuilder sb = new StringBuilder(tranKey);
                    switch (key) {
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_FINISH:
                            if (verify()) {
                                //完成
                                pop.dismiss();
                                Intent intent = new Intent();
                                intent.setClass(mContext, RepaymentPwdTwoActivity.class);
                                intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                                intent.putExtra("type", type);
                                startActivityForResult(intent, Constant.REQUST_CODE);
                            }
                            break;
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_DELETE:
                            //删除键
                            if (sb.length() > 0) {
                                sb.deleteCharAt(sb.length() - 1);
                            }
                            break;
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_ONE:
                            //数字键1
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_TWO:
                            //数字键2
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_THREE:
                            //数字键3
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_FOUR:
                            //数字键4
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_FIVE:
                            //数字键5
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_SIX:
                            //数字键6
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_SEVEN:
                            //数字键7
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_EIGHT:
                            //数字键8
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_NINE:
                            //数字键9
                        case RepayNumberKeyBoardPop.OnKeyPressed.KEY_ZERO:
                            //数字键0
                            sb.append(key);
                            break;
                    }
                    //限制6位验证码
                    if (sb.length() > 6) {
                        tranKey = sb.substring(0, 6);
                    } else {
                        tranKey = sb.toString();
                    }
                    if (tranKey.length() > 0) {
                        v_phone_code.setShowNum(tranKey.length(), tranKey.toCharArray());
                    } else {
                        v_phone_code.setShowNum(0, null);
                    }

                }
            });
        }
        if (!pop.isShowing()) {
            pop.showAtLocation(v_phone_code, Gravity.BOTTOM, 0, 0);
        }
    }

    private boolean verify() {
        if (!mPhone.isEmpty() && RegularUtil.isPhoneNumber(mPhone)) {
            if (TextUtils.isEmpty(tranKey)) {
                ToastUtil.showToast("请输入验证码");
                return false;
            } else {
                if (!tranKey.equals(msgCode)) {
                    ToastUtil.showToast("验证码错误");
                    return false;
                }
            }
        } else {
            ToastUtil.showToast("手机号不正确");
            return false;
        }
        return true;
    }

    //定时器
    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tv_code.setText("重新发送 （" + millisUntilFinished / 1000 + "）");
        }

        @Override
        public void onFinish() {
            tv_code.setText("点击重新发送");
            tv_code.setTextColor(ContextCompat.getColor(mContext, R.color.color_76ccfd));
            tv_code.setEnabled(true);
            timer = null;
        }
    }

    /**
     * 发送验证码
     *
     * @param phone
     */
    private void sendMsgCode(final String phone) {
        msgCode = String.valueOf(LoansUtils.getMsgCode());
        Observable<String> observable =
                Api.sendSms(phone, Constant.VERIFY_CODE_TYPE, msgCode,Constant.GDX030106);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
//                msgCode = "";
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject object = JSON.parseObject(s);
                if (object.getIntValue("status") == 1) {
                    senCode();
                    ToastUtil.showToast("验证码发送成功");
                    mPhone = phone;
                } else {
                    ToastUtil.showToast(object.getString("result"));
//                    msgCode = "";
                }
            }
        });
    }

    private void senCode() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new MyCountDownTimer(120l * 1000l, 1000L);
        timer.start();
        tv_code.setEnabled(false);
        tv_code.setText("重新发送 （120）");
        tv_code.setTextColor(ContextCompat.getColor(mContext, R.color.color_AFAFAF));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUST_CODE) {
            switch (resultCode) {
                case Constant.RESULT_CODE:
                    setResult(Constant.RESULT_CODE);
                    finish();
                    break;
            }
        }
    }
}
